package com.xps.and.yuntong.Ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xps.and.yuntong.Adapter.HotCityGridAdapter;
import com.xps.and.yuntong.Data.CityModel;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AssetsUitls;
import com.xps.and.yuntong.Utils.ChineseCharToEn;
import com.xps.and.yuntong.View.Custom.LetterListView;
import com.xps.and.yuntong.View.Custom.WheelView;
import com.jude.utils.JUtils;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 一个城市选择组件 这里更改用作汽车品牌选择
 * note
 * 取消 了搜索功能
 * 更改了数据源出口   getCityNames()返回的为汽车品牌数据
 */
public class CarBrandList extends Activity {
    private BaseAdapter adapter;
    private ListView mCityLit;
    private TextView overlay;
    private ImageView backbutton;
    private LetterListView letterListView;
    private HashMap<String, Integer> alphaIndexer;
    private String[] sections;
    private Handler handler;
    private OverlayThread overlayThread;
    //private SQLiteDatabase database;
    private ArrayList<CityModel> mCityNames;
    private View city_locating_state;
    private View city_locate_failed;
    private TextView city_locate_state;
    private ProgressBar city_locating_progress;
    private ImageView city_locate_success_img;
    View hotcityall;
    HashMap<String, ArrayList<String>> carbrandData = null;
    List<String> keyset = new ArrayList<>();
    String[] hotcity = new String[]{"丰田花冠", "大众桑塔纳", "大众捷达", "威志v5", "吉利远景", "现代索纳塔", "名图", "比亚迪f3", "雪铁龙爱丽舍"};
    WindowManager windowManager;
    public static int RESPONCE_CODE = 2;
    public static String RESPONCE_CITY = "city";
    public static String RESPONCE_CAR_BRAND = "NULL";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater localLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View city_layout = localLayoutInflater.inflate(R.layout.public_cityhot, null);
        setContentView(city_layout);
        backbutton = (ImageView) city_layout.findViewById(R.id.title_left_txt_btn);
        mCityLit = (ListView) city_layout.findViewById(R.id.public_allcity_list);
        letterListView = (LetterListView) city_layout.findViewById(R.id.cityLetterListView);

        View cityhot_header_blank = localLayoutInflater.inflate(R.layout.public_cityhot_header_padding_blank, mCityLit, false);
        // mCityLit.addHeaderView(cityhot_header_blank, null, false);
        cityhot_header_blank = localLayoutInflater.inflate(R.layout.city_locate_layout, mCityLit, false);
        city_locating_state = cityhot_header_blank.findViewById(R.id.city_locating_state);
        city_locate_state = ((TextView) cityhot_header_blank.findViewById(R.id.city_locate_state));
        city_locating_progress = ((ProgressBar) cityhot_header_blank.findViewById(R.id.city_locating_progress));
        city_locate_success_img = ((ImageView) cityhot_header_blank.findViewById(R.id.city_locate_success_img));
        city_locate_failed = cityhot_header_blank.findViewById(R.id.city_locate_failed);
        // mCityLit.addHeaderView(cityhot_header_blank);
        try {
            carbrandData = AssetsUitls.getInstance(this).getCarBrandMap();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        View hotheadview = localLayoutInflater.inflate(R.layout.public_cityhot_header_padding, mCityLit, false);
        mCityLit.addHeaderView(hotheadview, null, false);
        hotcityall = localLayoutInflater.inflate(R.layout.public_cityhot_allcity, mCityLit, false);
        final GridView localGridView = (GridView) hotcityall.findViewById(R.id.public_hotcity_list);

        mCityLit.addHeaderView(hotcityall);

        HotCityGridAdapter adapter = new HotCityGridAdapter(this, Arrays.asList(hotcity));
        localGridView.setAdapter(adapter);
        localGridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //热门
//                String cityModel = parent.getAdapter()
//                        .getItem(position).toString();
//                Setting.Save2SharedPreferences(CarBrandList.this, "city",
//                        cityModel);
//                Intent intent = new Intent();
//                intent.putExtra(RESPONCE_CITY, cityModel);
//                setResult(RESPONCE_CODE, intent);
//                finish();

//                StringBuilder str = new StringBuilder();
//                str.append(parent.getAdapter()
//                        .getItem(position).toString());
//                if (str.toString().equals("日产") || str.toString().equals("奥迪") || str.toString().equals("丰田") || str.toString().equals("现代") || str.toString().equals("本田") || str.toString().equals("别克") || str.toString().equals("起亚")) {
//                    str.append("(进口)");
//                }
//
//                if (str.toString().equals("大众")) {
//                    str.replace(0, str.length(), "一汽-大众");
//                }
//
//                initCarBrandChoose(str.toString());

                Intent intent = new Intent("com.nangch.broadcasereceiver.MYRECEIVER");
                intent.putExtra("getCouponId", adapter.getItem(position)+"");
                sendBroadcast(intent);
//              Log.e("initCarBrandChoose", adapter.getItem(position)+"");
                finish();

            }
        });

        city_locating_state.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String cityModel = city_locate_state.getText().toString();
//                Setting.Save2SharedPreferences(CarBrandList.this, "city",
//                        cityModel);
//                Intent intent = new Intent(CarBrandList.this, NewCarAuthActivity.class);
//                intent.putExtra(RESPONCE_CAR_BRAND, cityModel);
//                setResult(RESPONCE_CODE, intent);
//                finish();
            }
        });

        // loadLocation();

//        DBManager dbManager = new DBManager(this);
//        dbManager.openDateBase();
//        dbManager.closeDatabase();

//        database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
//                + DBManager.DB_NAME, null);
        mCityNames = getCityNames();
        //database.close();
        letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
        alphaIndexer = new HashMap<String, Integer>();
        handler = new Handler();
        overlayThread = new OverlayThread();
        initOverlay();
        setAdapter(mCityNames);
        mCityLit.setOnItemClickListener(new CityListOnItemClick());
        backbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                String city = data.getStringExtra("city");
                Intent intent = new Intent();
                intent.putExtra(RESPONCE_CITY, city);
                setResult(RESPONCE_CODE, intent);
                finish();
                break;

            default:
                break;
        }
    }

    /**
     * @return
     */
    private ArrayList<CityModel> getCityNames() {
        ArrayList<CityModel> names = new ArrayList<CityModel>();

        Iterator<String> i = carbrandData.keySet().iterator();
        while (i.hasNext()) {
            keyset.add(i.next());
        }

        for (int ii = 0; ii < keyset.size(); ii++) {
            CityModel cityModel = new CityModel();
            String str = keyset.get(ii);
            cityModel.setCityName(str);
            cityModel.setNameSort(ChineseCharToEn.getAllFirstLetter(str.charAt(0) + "").toUpperCase());

            names.add(cityModel);
        }

        Collections.sort(names);

        for (CityModel c : names) {
            JUtils.Log(c.toString());
        }

        return names;
    }

    /**
     * б 1/4
     *
     * @author
     */
    class CityListOnItemClick implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                                long arg3) {
            CityModel cityModel = (CityModel) mCityLit.getAdapter()
                    .getItem(pos);

            initCarBrandChoose(cityModel.getCityName());
//            if (cityModel != null) {
//                Setting.Save2SharedPreferences(CarBrandList.this, "city",
//                        cityModel.getCityName());
//                Intent intent = new Intent();
//                intent.putExtra(RESPONCE_CITY, cityModel.getCityName());
//                setResult(RESPONCE_CODE, intent);
//                finish();
        }
    }

    /**
     * ListView
     *
     * @param list
     */
    private void setAdapter(List<CityModel> list) {
        if (list != null) {
            adapter = new ListAdapter(this, list);
            mCityLit.setAdapter(adapter);
        }

    }

    /**
     * ListViewAdapter
     *
     * @author gugalor
     */
    private class ListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private List<CityModel> list;

        public ListAdapter(Context context, List<CityModel> list) {

            this.inflater = LayoutInflater.from(context);
            this.list = list;
            alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];

            for (int i = 0; i < list.size(); i++) {
                //
                // getAlpha(list.get(i));
                String currentStr = list.get(i).getNameSort();
                //
                String previewStr = (i - 1) >= 0 ? list.get(i - 1)
                        .getNameSort() : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = list.get(i).getNameSort();
                    alphaIndexer.put(name, i);
                    sections[i] = name;
                }
            }
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.public_cityhot_item,
                        null);
                holder = new ViewHolder();
                holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
                holder.name = (TextView) convertView
                        .findViewById(R.id.public_cityhot_item_textview);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.name.setText(list.get(position).getCityName());
            String currentStr = list.get(position).getNameSort();
            String previewStr = (position - 1) >= 0 ? list.get(position - 1)
                    .getNameSort() : " ";
            if (!previewStr.equals(currentStr)) {
                holder.alpha.setVisibility(View.VISIBLE);
                holder.alpha.setText(currentStr);
            } else {
                holder.alpha.setVisibility(View.GONE);
            }
            return convertView;
        }

        private class ViewHolder {
            TextView alpha;
            TextView name;
        }
    }

    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    @Override
    protected void onDestroy() {
        windowManager.removeView(overlay);
        super.onDestroy();
    }

    private class LetterListViewListener implements
            LetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                mCityLit.setSelection(position);
                overlay.setText(sections[position]);
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // Уoverlay
                handler.postDelayed(overlayThread, 1500);
            }
        }

    }

    // overlay
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    void initCarBrandChoose(final String carBrand) {
        final StringBuilder sb = new StringBuilder();
        sb.append(carBrand);
        sb.append("-");
        final ArrayList<String> arrayList = carbrandData.get(carBrand);
        if (arrayList == null) return;

        final strB s = new strB();

        View car_brand_outer_view = LayoutInflater.from(CarBrandList.this).inflate(R.layout.car_brand_choose_single, null);
        final WheelView wv_carbrand = (WheelView) car_brand_outer_view.findViewById(R.id.wv_carbrand);
        wv_carbrand.setOffset(3);
        wv_carbrand.setItems(arrayList);
        wv_carbrand.setSeletion(0);
        wv_carbrand.setOnWheelViewListener(new WheelView.OnWheelViewListener() {

            @Override
            public void onSelected(int selectedIndex, String item) {
                s.setCar(item);
            }
        });

        new AlertDialog.Builder(CarBrandList.this)
                .setTitle(carBrand)
                .setView(car_brand_outer_view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //Refrence to : XSLicenseFragment
                        if ("".equals(s.getCarB())) {
                            sb.append(arrayList.get(0));
                        } else
                            sb.append(s.getCarB());
                        //EventBus.getDefault().post(new CarbrandChooseResult(sb.toString(), 0));
                        Intent intent = new Intent("com.nangch.broadcasereceiver.MYRECEIVER");
                        intent.putExtra("getCouponId", sb.toString());
                        sendBroadcast(intent);
                        Log.e("initCarBrandChoose", sb.toString());
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    class strB {
        String car = "";

        public String getCarB() {
            return car;
        }

        public void setCar(String car) {
            this.car = car;
        }

        public strB() {
        }
    }

}